import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.usermodel.*;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainClass {

    public static void main(String[] args){
        //接口地址
        String apiUrl = "http://172.18.118.4:8000/detect";
        //图片文件地址
        String folderPath = "D:\\Desktop\\DZYY20250827\\XC_tm\\qx";
        //对照文件地址
        String excelPath = "D:\\Desktop\\DZYY20250827\\XC_tm\\realxiammaqx.xlsx";
        List<String> allFiles = getAllFiles(folderPath);
        for (String imagePath : allFiles) {
            try {
                uploadImage(apiUrl, imagePath,excelPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取目录下所有文件
     * @param folderPath
     * @return
     */
    public static List<String> getAllFiles(String folderPath) {
        List<String> fileList = new ArrayList<>();
        File folder = new File(folderPath);
        if (!folder.exists() || !folder.isDirectory()) {
            System.err.println("路径不存在或不是文件夹");
            return fileList;
        }
        scanFolder(folder, fileList);
        return fileList;
    }

    /**
     * 递归得到目录下所有文件
     * @param folder
     * @param fileList
     */
    private static void scanFolder(File folder, List<String> fileList) {
        File[] files = folder.listFiles();
        if (files == null) return;

        for (File file : files) {
            if (file.isDirectory()) {
                scanFolder(file, fileList); // 递归处理子文件夹
            } else {
                fileList.add(file.getAbsolutePath());
            }
        }
    }

    public static void uploadImage(String apiUrl, String imagePath,String excelPath) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(apiUrl);

            // 构建multipart/form-data请求体
            File imageFile = new File(imagePath);
            FileBody fileBody = new FileBody(imageFile,ContentType.create("image/" +imagePath));
            HttpEntity entity = MultipartEntityBuilder.create()
                    .addPart("file", fileBody)  // "file"为接口定义的参数名
                    .build();

            httpPost.setEntity(entity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                JSONObject jsonObj = new JSONObject(EntityUtils.toString(response.getEntity()));
                JSONArray dataArray = jsonObj.getJSONArray("data");
                String sealValue = null;
                if(dataArray.length()==1){
                    sealValue = dataArray.getJSONObject(0).getString("seal");
                }else if(dataArray.length()>1){
                    for(int i=0;i<dataArray.length();i++){
                        if(i==0){
                            sealValue =  dataArray.getJSONObject(i).getString("seal");
                        }else{
                            sealValue = sealValue +"|"+dataArray.getJSONObject(i).getString("seal");
                        }
                    }
                }else {
                    sealValue = null;
                }
                //获取原小码并对比
                String realxiaoma = findRowsByColumn(excelPath,0,0,imageFile.getName());
                String isYiZhi = "否";

                if(!"".equals(realxiaoma) && realxiaoma!= null && !"".equals(sealValue) && sealValue!= null ){
                    String[] ary1 = realxiaoma.split("|");
                    String[] ary2 = sealValue.split("|");
                    if(ary1.length>1 && ary2.length>1){
                        List<String> list1 = Arrays.asList(ary1);
                        List<String> list2 = Arrays.asList(ary2);
                        boolean isEqual = CollectionUtils.isEqualCollection(list1, list2); // 返回 true
                        if(isEqual==true){
                            isYiZhi = "是";
                        }
                    }else {
                        if(realxiaoma.equals(sealValue)){
                            isYiZhi = "是";
                        }
                    }
                }

                System.out.println(imageFile.getName()+"||"+isYiZhi+"||"+sealValue);
            }
        }
    }

    /**
     * 根据字段得到行信息
     * @param filePath
     * @param sheetIndex
     * @param columnIndex
     * @param searchValue
     * @return
     */
    public static String findRowsByColumn(String filePath, int sheetIndex,int columnIndex, String searchValue) {
        String rel = "";
        try (Workbook workbook = WorkbookFactory.create(new File(filePath))) {
            Sheet sheet = workbook.getSheetAt(sheetIndex);
            for (Row row : sheet) {
                Cell cell = row.getCell(columnIndex);
                if (cell != null && !"".equals(cell) && cell.toString().equals(searchValue)) {
                    rel = row.getCell(1)+"";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rel;
    }
}
